// pages/product/detail/detail.js
import MallService from "../../../class/service/MallService";
import OrderService from "../../../class/service/OrderService";
import ProductService from "../../../class/service/ProductService";
import SmsService from "../../../class/service/SmsService";
import Router from "../../../class/Router";
import Tips from "../../../utils/Tips";

const util = require("../../../utils/util.js")
const storage = require("../../../utils/storage.js")
const constant = require("../../../constant.js")
const notification = require("../../../utils/WxNotificationCenter.js");

const mallService = new MallService();
const orderService = new OrderService();
const productService = new ProductService();
const smsService = new SmsService();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    init: false,
    needMobile: false,
    selfCourse: 0,
    codeMsg: '获取验证码'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    var that = this;
    var unionid = wx.getStorageSync(storage.keys.unionid);
    that.setData({
      unionid: unionid
    })

    var openid = wx.getStorageSync(storage.keys.openid);
    that.setData({
      openid: openid
    })

    var mobile = wx.getStorageSync(storage.keys.mobile);
    that.setData({
      mobile: mobile
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;

    var imgsrc = 'http://aipunet.qiniu.edooschool.com/downpour-wechat.png?' + new Date().getTime();
    this.setData({
      img: imgsrc
    })

    if(that.data.mobile) {
      that.initData()
    } else {
      that.setData({
        init: false,
        needMobile: true
      })
    }


  },

  initData: function() {
    var that = this;
    Tips.loading();

    mallService.list().then(data => {

      Tips.loaded();

      that.setData({
        "skus": data.skus
      })

      orderService.list(that.data.unionid).then(data => {

        that.setData({
          "skuIds": data.skuIds,
          "salesOrders": data.salesOrders,
          "init": true
        })

        that.mergeSku()

        productService.listByPersion(that.data.unionid).then(data => {
          Tips.loaded();
          that.setData({
            "init": true,
            "userCourses": data.userCourses,
            "selfCourse": data.userCoursesSize
          })

        }, res => {
          Tips.error("获取练习失败");
          that.setData({
            "init": true,
            "selfCourse": 0
          })
        })

      }, res => {
        Tips.error("获取已购订单详情失败");
          that.setData({
            "init": true
          })
      })


    }, res => {
      Tips.error("获取商品详情失败");
      that.setData({
        "init": true
      })
    })
    
    // productService.list().then(data => {
    //   that.setData({
    //     "courses": data.courses,
    //   })

    //   productService.listByPersion(that.data.unionid).then(data => {
    //     Tips.loaded();
    //     that.setData({
    //       "init": true,
    //       "userCourses": data.userCourses,
    //       "selfCourse": data.userCoursesSize
    //     })

    //     that.mergeCourse();

        

    //   }, res => {
    //     Tips.error("获取练习失败");
    //     that.setData({
    //       "init": true,
    //       "selfCourse": 0
    //     })
    //   })


    // }, res => {
    //   Tips.error("获取练习失败");
    //   that.setData({
    //     "init": true,
    //     "selfCourse": 0
    //   })
    // })
  },

  mergeSku: function() {
    var that = this;
    var skus = that.data.skus;
    var skuIds = that.data.skuIds;
    var result = [];
    for (var i in skus) {
      var sku = skus[i];
      for(var j in skuIds) {
        if(sku.id == skuIds[j]) {
          skus[i]['paid'] = true
        }
      }
    }
    console.log(skus)
    that.setData({
      skus: skus
    })
  },

  mergeCourse: function() {
    var that = this;
    var userCourses = that.data.userCourses;
    var courses = that.data.courses;
    var result = [];
    for (var i in courses) {
      var course = courses[i];
      if (userCourses && userCourses[course.id] != null) {
        course['paid'] = true
      }
      result.push(course)
    }

    that.setData({
      courses : result
    })
    
  },

  onInputPhone: function (e) {
    var that = this;
    that.setData({
      phone: e.detail
    })
  },

  inputCode: function (e) {
    var that = this;
    that.setData({
      code: e.detail
    })
    if (that.data.code.length == 6) {
      that.bindUser();
    }
  },

  /**
   * 跳转到详情页面
   */
  goToDetials: function (e) {
    var id = e.currentTarget.dataset.id;
    var paid = e.currentTarget.dataset.paid;
    if (paid) {
      wx.navigateTo({
        url: '../../../../pages/product/unit-list/unit-list?id=' + id
      });
    } else {
      Tips.confirm("您还未购买该课程, 点击确定联系陆老师购买~", { skuId: id }, "温馨提示").then(data => {
        console.log(data);
        wx.navigateTo({
          url: '../../../../pages/downpour/downpour',
        })
      }, res => {
        console.log(res);
      })
    }
  },

  bindUser: function () {
    var that = this;
    
    smsService.bindUser(that.data.unionid, that.data.phone, that.data.code, that.data.token, that.data.openid).then(data => {
      that.setData({
        mobile: data.user.mobile
      })
      wx.setStorageSync(storage.keys.mobile, that.data.mobile)
      that.setData({
        init: false,
        needMobile: false
      })
      that.initData();
    }, res => {
      Tips.error("绑定验证码失败");
      that.setData({
        disableGetCode: false,
        codeMsg: "获取验证码"
      })
    })
  },

  validMobile: function () {
    var that = this;
    if (!that.data.phone) {
      that.showMessage("请先输入手机")
      return false;
    } else if (!/^((13)|(14)|(15)|(16)|(17)|(18)|(19))\d{9}$/.test(that.data.phone)) {
      that.showMessage("请输入正确的手机")
      return false;
    }

    return true;
  },

  onSendSms: function (event) {

    var that = this;
    if (that.validMobile()) {

      that.setData({
        disableGetCode: true
      })

      var seconds = 60;
      var interval = setInterval(function (e) {
        seconds--;
        if (seconds < 0) {
          that.setData({
            disableGetCode: false,
            codeMsg: "重新获取验证码"
          })
          clearInterval(interval);
        } else {
          that.setData({
            codeMsg: "发送中（" + seconds + "）秒"
          })
        }
      }, 1000)

      smsService.send(that.data.phone).then(data => {
        that.setData({
          token: data.token
        })
        Tips.loaded();
      }, res => {
        Tips.error("获取验证码失败");
        that.setData({
          disableGetCode: false,
          codeMsg: "获取验证码"
        })
        clearInterval(interval);
      });
    }
  },

  showMessage: function (text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function () {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onSaveImage: function () {
    console.log("123");
    var that = this;
    // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.record" 这个 scope
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              wx.downloadFile({
                url: that.data.img, // 仅为示例，并非真实的资源
                success(res) {
                  console.log(res)
                  // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                  if (res.statusCode === 200) {
                    // wx.playVoice({
                    //   filePath: res.tempFilePath
                    // })
                    wx.saveImageToPhotosAlbum({
                      filePath: res.tempFilePath,
                      success(res) {
                        console.log("保存成功")
                      }
                    })
                  }
                }
              })
            }
          })
        } else {
          // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
          wx.downloadFile({
            url: that.data.img, // 仅为示例，并非真实的资源
            success(res) {
              console.log(res)
              // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
              if (res.statusCode === 200) {
                // wx.playVoice({
                //   filePath: res.tempFilePath
                // })
                wx.saveImageToPhotosAlbum({
                  filePath: res.tempFilePath,
                  success(res) {
                    console.log("保存成功")
                  }
                })
              }
            }
          })
        }
      }
    })
  },

  /**
   * 跳转到详情页面
   */
  goToDetials: function (e) {
    var id = e.currentTarget.dataset.id;
    var paid = e.currentTarget.dataset.paid;
    if(paid) {
      wx.navigateTo({
        url: '../../../pages/product/unit-detail/unit-detail?id=' + id
      });
    } else {
      Tips.confirm("您还未购买该课程, 点击确定联系陆老师购买~", {skuId: id}, "温馨提示").then(data => {
        console.log(data);
        wx.navigateTo({
          url: '../../../pages/downpour/downpour',
        })
      }, res => {
        console.log(res);
      })
    }
  }
});
